package com.awspaas.user.apps.cpq.event;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.math.NumberUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.bpmn.engine.core.delegate.ProcessExecutionContext;
import com.actionsoft.bpms.bpmn.engine.listener.ExecuteListener;
import com.actionsoft.bpms.bpmn.engine.listener.ListenerConst;
import com.actionsoft.bpms.commons.database.RowMap;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.sdk.local.SDK;
import com.alibaba.fastjson.JSONObject;

public class ModuleRecordFormAfterSave extends ExecuteListener {

	public ModuleRecordFormAfterSave() {
		setDescription("模块记录清单中，点击保存按钮后，自动计算物料价格和直发物资价格");
	}

	@Override
	public void execute(ProcessExecutionContext pec) throws Exception {
		Workbook workbookwl = new XSSFWorkbook();
		try {
			String bindId = pec.getProcessInstance().getId();
			// BO表名
			String boName = pec.getParameterOfString(ListenerConst.FORM_EVENT_PARAM_BONAME);
			 if(boName.equals("BO_EU_CPQ_MODULE_RECORD")) {
				 BO data=SDK.getBOAPI().query("BO_EU_CPQ_MODULE_RECORD").bindId(bindId).detail();
		        	//List<BO> bos=(List) pec.getParameter(ListenerConst.FORM_EVENT_PARAM_GRIDDATA);
				 List<BO> bos=SDK.getBOAPI().query("BO_EU_CPQ_MODULE_RECORD_GRID").bindId(bindId).list();
				 List<BO> list=SDK.getBOAPI().query("BO_EU_CPQ_MODULE_RECORD_PARAMETERS").bindId(bindId).list();
				// 获取模块所需参数信息
					Map<String, JSONObject> pMap = new HashMap<String, JSONObject>();
					Map<String, String> nameMap = new HashMap<String, String>();
					Map<String, String> noMap = new HashMap<>();
					for (int i = 0; i < list.size(); i++) {
						//JSONObject json = (JSONObject) list.get(i);
						BO json = list.get(i);
						String bh = (String) json.get("PARMENTIER_NO");
						String value = (String) json.get("PARMENTIER_VALUE");
						String name = (String) json.get("PARMENTIER_NAME");
						String dw = (String) json.get("DW");
						JSONObject jsonObject=new JSONObject();
						//判断value是否为数据
						if( NumberUtils.isCreatable(value)) {
							jsonObject.put("type", "1");//值为1者表示value为数值
						}else {
							jsonObject.put("type", "0");//值为0者表示value为字符串
						}
						jsonObject.put("value", value);
						pMap.put(bh, jsonObject);
						nameMap.put(bh, name);
						int num = i + 1;
						noMap.put(bh, "B$" + num);
					}
					// 设置参数值到单元格中
					Sheet sheet = workbookwl.createSheet("Sheet1");
					for (int i = 0; i < list.size(); i++) {
						int num = i + 1;
						Cell cellB1 = sheet.createRow(i).createCell(1);
						//JSONObject jsonObject = (JSONObject) list.get(i);
						BO jsonObject =  list.get(i);
						String bh = (String) jsonObject.get("PARMENTIER_NO");
						JSONObject jsonObject2=	pMap.get(bh);
						String type=jsonObject2.getString("type");
						if(type.equals("0")) {
							cellB1.setCellValue(jsonObject2.getString("value"));
							System.out.println("cellB1:"+cellB1.getStringCellValue());
						}else {
							String value=jsonObject2.getString("value");
							double  numValue=Double.parseDouble(value);		
							 cellB1.setCellValue(numValue);
							 System.out.println("cellB1:"+cellB1.getNumericCellValue());
						}
					}
		         String type=data.getString("CJLX");	
		       //获取模块中物料信息，对物料信息进行更新和计算，如果数量没有值，只更新物料信息；
		            String  wpsql="select  a.BM,a.NAME,a.TYPE,a.GG,a.TH,a.DW,a.ZL,a.TJ,"
		            		+ "a.CLF,"
		            		+ "a.RGF,a.WXWG,a.CGF,a.DJ,b.SL,b.ID "
		            		+ "from   BO_EU_CPQ_COMPONENT_PART a ,BO_EU_CPQ_MODULE_RECORD_GRID b "
		            		+ "where  a.BM=b.WLBM and a.STATUS='启用' and b.BINDID=?";
		        	List<RowMap> maps=DBSql.getMaps(wpsql, new Object[] {bindId});
		        	Map<String, RowMap> newMap=new HashMap<String, RowMap>();	           
		            BigDecimal mkdj = new BigDecimal("0");	           
		            BigDecimal clf = new BigDecimal("0");	            
		            BigDecimal rgf = new BigDecimal("0");
		            BigDecimal wx = new BigDecimal("0");
		            BigDecimal cgf = new BigDecimal("0");
		            BigDecimal zfwzyf = new BigDecimal("0");
		            List<String> lists=new ArrayList<String>();
		            //更新物流信息
		            if(maps.size()>0) {
		        		for (RowMap rowMap : maps) {
							newMap.put(rowMap.getString("ID"), rowMap);
						}
		        		//更新模块物料数据
		        		if(bos.size()>0) {
		        			//对模块中有计算公式的物料进行数量计算
		        			for (int i = 0; i < bos.size(); i++) {
		        				BO bo =  bos.get(i);
		        				String id=bo.getId();
		        				
		        			     if(newMap.containsKey(id)) {
		        			    	 RowMap rowMap=	newMap.get(id);
		        			    	 String price1 = rowMap.getString("DJ").isEmpty()?"0":rowMap.getString("DJ");						
			        				 String clf1 = rowMap.getString("CLF").isEmpty()?"0":rowMap.getString("CLF");
			        				 String rgf1 = rowMap.getString("RGF").isEmpty()?"0":rowMap.getString("RGF");	
			        				String wx1 = rowMap.getString("WXWG").isEmpty()?"0":rowMap.getString("WXWG");	
			        			     String cgf1 = rowMap.getString("CGF").isEmpty()?"0":rowMap.getString("CGF");
		 						    String NAME=rowMap.getString("NAME");
								 
								    String TYPE=rowMap.getString("TYPE");
								   
								    String GG=rowMap.getString("GG");
								   
								    String TH=rowMap.getString("TH");
								   
								    String DW=rowMap.getString("DW");
								   
								    String ZL=rowMap.getString("ZL");
								   
								    String TJ=rowMap.getString("TJ");
								    
								    String CLF=rowMap.getString("CLF");
								   			   
								    String RGF=rowMap.getString("RGF");
								  
								    String WXWG=rowMap.getString("WXWG");
								    
								    String CGF=rowMap.getString("CGF");
								  
								    String DJ=rowMap.getString("DJ");
								   
					   			     double total1 = 0;					
				        			double clfnum1 = 0;					
				        			double rgfnum =0 ;
				        			double wxnum =0;
				        			double cgfnum =0 ;
				        				String equation = bo.getString("WLJSGS");
				        				String sl=bo.getString("SL").isEmpty()?"0":bo.getString("SL");
				        				Document document = Jsoup.parse(equation);
				        				String newQuation=document.text();

				        				if (!newQuation.equals("0")&&!newQuation.isEmpty()) {						
				        					System.out.println("参数计算公式："+newQuation);
				        					// 获取物料数量计算公式中参数代号，如果有则将代号存放在list中
				        					for (String key : pMap.keySet()) {
				        						int num = newQuation.indexOf(key);
				        						if (num > -1) {
				        							newQuation = newQuation.replace(key, noMap.get(key));
				        						}
				        					}
				        					System.out.println("转换后的参数计算公式："+newQuation);
				        					// 计算出物料数量和当前模块的物料成本价格
				        					FormulaEvaluator formulaEvaluator = workbookwl.getCreationHelper().createFormulaEvaluator();
				        					Cell cellB1 = sheet.createRow(list.size()+1+i).createCell(2);
				        					cellB1.setCellFormula(newQuation);
				        					formulaEvaluator.evaluateFormulaCell(cellB1);
				        					// 获取公式计算结果
				        					CellValue cellValue = formulaEvaluator.evaluate(cellB1);
				        					System.out.println("The result of the formula is: " + cellValue.getNumberValue());
				        					//String tj = json.getString("TJ").isEmpty()?"0":json.getString("TJ");	
				        					//String zl = json.getString("ZL").isEmpty()?"0":json.getString("ZL");	
				        					 total1 = Double.parseDouble(price1) * cellValue.getNumberValue();					
				        					 clfnum1 = Double.parseDouble(clf1) * cellValue.getNumberValue();					
				        					 rgfnum = Double.parseDouble(rgf1) * cellValue.getNumberValue();
				        					 wxnum = Double.parseDouble(wx1) * cellValue.getNumberValue();
				        					 cgfnum = Double.parseDouble(cgf1) * cellValue.getNumberValue();
				        					//double tjnum = Double.parseDouble(tj) * cellValue.getNumberValue();
				        					//double zlnum = Double.parseDouble(zl) * cellValue.getNumberValue();
				        			         sl=String.valueOf(cellValue.getNumberValue());
				        				}else {
				        					  double num= Double.parseDouble(sl);	
				        					   total1 = Double.parseDouble(price1) * num;					
					        				  clfnum1 = Double.parseDouble(clf1) * num;					
					        				   rgfnum = Double.parseDouble(rgf1) * num;
					        				   wxnum = Double.parseDouble(wx1) * num;
					        				   cgfnum = Double.parseDouble(cgf1) * num;
				        					 
				        				}
										 String upSql= "update BO_EU_CPQ_MODULE_RECORD_GRID set WLMC='"+NAME+"',LX='"+TYPE+"',GG='"+GG+"',"
										 		+ "DH='"+TH+"',DW='"+DW+"',DJ='"+DJ+"',CGF= '"+CGF+"',CLF= '"+CLF+"' ,RGF='"+RGF+"',WXWG='"+WXWG+"'"
										 		+ ",SL='"+sl+"',ZJ='"+total1+"',ZCLF='"+clfnum1+"',ZGSF='"+rgfnum+"',ZWX='"+wxnum+"',ZCGF='"+cgfnum+"' where ID='"+id+"' ; ";
                                         lists.add(upSql);;
     				        			  BigDecimal total = new BigDecimal(total1);	
     				        			  BigDecimal clfnum = new BigDecimal(clfnum1);	
     				        			  BigDecimal rgfnum1 = new BigDecimal(rgfnum);	
     				        			  BigDecimal wxnum1 = new BigDecimal(wxnum);	
     				        			  BigDecimal cgfnum1 = new BigDecimal(cgfnum);    				        			 
     				        			 mkdj= mkdj.add(total);  	 
     				        			clf=  clf.add(clfnum);
     				        			rgf=rgf.add(rgfnum1);
     				        			wx=wx.add(wxnum1);     						           
     				        			cgf=cgf.add(cgfnum1);
		        			     }
		     
		        			}
		        			
		        		}
		            }
		        	//获取直发物资运费
		        	List<BO> zfs=SDK.getBOAPI().query("BO_EU_BO_EU_CPQ_MODULE_MSG_STRAIGHT_HAIR").bindId(bindId).list();
		        	 BigDecimal ZFYF = new BigDecimal("0");	 
		        	List<String> sqlLists=new ArrayList<>();
		        	if(zfs.size()>0) {
		        		for (int i = 0; i < zfs.size(); i++) {
		        			BO bo2=zfs.get(i); 
		        			String sljsgs=bo2.getString("JSGS");//直发运费数量计算公式；
		        			String yfdj=bo2.getString("YFBZ").isEmpty()?"0":bo2.getString("YFBZ");//运费单价；
		        			 String SL=bo2.getString("SL").isEmpty()?"0":bo2.getString("SL");//运费单价；
		        			 BigDecimal price = new BigDecimal(yfdj);	
		        			 BigDecimal sl = new BigDecimal(SL);
						    					    
						    Document document = Jsoup.parse(sljsgs);
							String newQuation=document.text();
							 if (!newQuation.equals("0")&&!newQuation.isEmpty()) {
								  for (String key : pMap.keySet()) {
										int num = newQuation.indexOf(key);
										if (num > -1) {
											newQuation = newQuation.replace(key, noMap.get(key));
										}
									}
								  FormulaEvaluator formulaEvaluator = workbookwl.getCreationHelper().createFormulaEvaluator();
									Cell cellB1 = sheet.createRow(list.size()+bos.size()+1+i).createCell(2);
									cellB1.setCellFormula(newQuation);
									formulaEvaluator.evaluateFormulaCell(cellB1);
									// 获取公式计算结果
									CellValue cellValue = formulaEvaluator.evaluate(cellB1);
									System.out.println("The result of the formula is: " + cellValue.getNumberValue());																		
									BigDecimal num = new BigDecimal(cellValue.getNumberValue());
									ZFYF=ZFYF.add(num.multiply(price));
									 String upSql= "update BO_EU_CPQ_MODULE_RECORD_STRAIGHT_HAIR set SL= '"+cellValue.getNumberValue()+"',YFJG= '"+num.multiply(price)+"'  where ID='"+bo2.getString("ID")+"' ; ";
										//upSql=String.format(upSql, cldjNew,clfNew,zjNew,zclfNew,ID);
										sqlLists.add(upSql);

						}else {
							//String sl=bo2.getString("SL").isEmpty()?"0":bo2.getString("SL");//运费数量;
							 //double num=Double.parseDouble(sl);
							 ZFYF=ZFYF.add(price.multiply(sl));	
						} 
						    
						    
						}
		        	}
		        	mkdj=mkdj.add(ZFYF);
		            String bl=data.getString("ZZFBL").isEmpty()?"0":data.getString("ZZFBL");		    					
					BigDecimal blnum = new BigDecimal(bl);
					BigDecimal num = new BigDecimal("100");
					BigDecimal num1 = new BigDecimal("1");
					BigDecimal zzf=	clf.add(rgf).divide(num1.subtract(blnum.divide(num)), 4).multiply(blnum.divide(num));
					data.set("ZZF", zzf);
					data.set("DJZZF", zzf.add(mkdj));
					data.set("MKDJ", mkdj);	        			
		        	data.set("CLF",clf);	    	        	
		        	data.set("RGF", rgf);
		        	data.set("WXWG", wx);
		        	data.set("CGF", cgf);
		        	data.set("ZFWZYF", ZFYF);
					//计算模块数量
					//计算模块数量
					
					String jsgs=data.getString("SLJSGZ");//模块数量计算公式；
					Document document = Jsoup.parse(jsgs);
					String newQuation=document.text();
					if (!newQuation.equals("0")&&!newQuation.isEmpty()) {
						  for (String key : pMap.keySet()) {
								int num3 = newQuation.indexOf(key);
								if (num3 > -1) {
									newQuation = newQuation.replace(key, noMap.get(key));
								}
							}
						  FormulaEvaluator formulaEvaluator = workbookwl.getCreationHelper().createFormulaEvaluator();
							Cell cellB1 = sheet.createRow(list.size()+bos.size()+3).createCell(2);
							cellB1.setCellFormula(newQuation);
							formulaEvaluator.evaluateFormulaCell(cellB1);
							// 获取公式计算结果
							CellValue cellValue = formulaEvaluator.evaluate(cellB1);
							System.out.println("The result of the formula is: " + cellValue.getNumberValue());
							data.set("MKSL", cellValue.getNumberValue());
							
						
					  }
					SDK.getBOAPI().update("BO_EU_CPQ_MODULE_RECORD", data);
					if(lists.size()>0) {						
						 String[] array3 = lists.toArray(new String[lists.size()]);	
						DBSql.batch(array3);
					}
					if(sqlLists.size()>0) {						
						 String[] array3 = sqlLists.toArray(new String[sqlLists.size()]);	
						DBSql.batch(array3);
					}
			 }
		} catch (Exception e) {
			throw e;
		}
	}

}
